package com.symbio.ishenapi.background.controller;


import com.jfinal.ext.kit.DateKit;
import com.jfinal.plugin.activerecord.Record;
import com.symbio.ishenapi.background.model.TmDoctorInsuranceCorps;
import com.symbio.ishenapi.background.model.TmInsuranceCorps;
import com.symbio.ishenapi.background.model.TmMedicalAssistance;
import com.symbio.ishenapi.background.model.base.PersonScheduling;
import com.symbio.ishenapi.common.controller.BaseController;
import io.jboot.web.controller.annotation.RequestMapping;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 保险团
 */
@RequestMapping("/tmInsuranceCorpsController")
public class TmInsuranceCorpsController extends BaseController {


    /**
     * 查询全部保险团信息
     */
    public void findAll(){
        Map map = TmInsuranceCorps.dao.findAll(getQueryModel());
        renderPageJsonRet(map.get("count"),map.get("data"));
    }


    /**
     * 修改删除状态
     */
    public void updateStatus() {
        TmInsuranceCorps user = (TmInsuranceCorps) getReqBodyObject(TmInsuranceCorps.class);
        TmInsuranceCorps u = TmInsuranceCorps.dao.findById(user.getId());
        if (u != null) {
            u.setStatus(user.getStatus());
            if (u.update()) {
                renderJsonRet(user.getId());
            } else {
                renderJsonError(40005);
            }
        } else {
            renderJsonError(40003);
            return;
        }
    }


    /**
     * 根据id获取保险团信息
     */
    public void findById() {
        // TmInsuranceCorps user = (TmInsuranceCorps) getReqBodyObject(TmInsuranceCorps.class);
        String id = getPara("id");
        TmInsuranceCorps tmInsuranceCorps = TmInsuranceCorps.dao.findById(new BigInteger(id));//获取保险团

        if (tmInsuranceCorps != null) {
            /*Map map = TmDoctorInsuranceCorps.dao.findDoctorInsuranceCorpsByInsuranceCorpsId(tmInsuranceCorps.getId(),getQueryModel());//获取保险团成员
        *//*  Map<String,Object> map = new HashMap();

          map.put("tmDoctorInsuranceCorpsList",tmDoctorInsuranceCorpsList);
            renderJsonRet(map);*//*
            map.put("tmInsuranceCorps",tmInsuranceCorps);
            renderPageJsonRet(map.get("count"),map.get("data"));*/
            renderJsonRet(tmInsuranceCorps);
        } else {
            renderJsonError(40003);
            return;
        }
    }


    /**
     *
     * 获取保险团成员列表
     */
    public void findByInsuranceCorps() {
        // TmInsuranceCorps user = (TmInsuranceCorps) getReqBodyObject(TmInsuranceCorps.class);
        String id = getPara("id");
        TmInsuranceCorps tmInsuranceCorps = TmInsuranceCorps.dao.findById(new BigInteger(id));//获取保险团

        if (tmInsuranceCorps != null) {
            Map map = TmDoctorInsuranceCorps.dao.findDoctorInsuranceCorpsByInsuranceCorpsId(tmInsuranceCorps.getId(),getQueryModel());//获取保险团成员
            renderPageJsonRet(map.get("count"),map.get("data"));
        } else {
            renderJsonError(40003);
            return;
        }
    }

    /**
     * 保存保险团信息
     */
    public void save() {
        TmInsuranceCorps user = (TmInsuranceCorps) getReqBodyObject(TmInsuranceCorps.class);
        List<TmInsuranceCorps> tmInsuranceCorpsList = TmInsuranceCorps.dao.findByCodeList(user.getInsuranceCorpsCode());
        user.setStatus(1L);
        user.setCreateTime(new Date());
        user.setInsuranceCorpsNumber(0L);
        if(tmInsuranceCorpsList.size() <= 0 || tmInsuranceCorpsList == null){
            if (user.save()) {
                renderJsonRet(40001);
            } else {
                renderJsonError(40003);
                return;
            }
        }else{
            renderJsonError(40015,"保险团编号");
            return;
        }

    }

    /**
     * 修改保险团信息
     */
    public void updateTmInsuranceCorps() {
        TmInsuranceCorps user = (TmInsuranceCorps) getReqBodyObject(TmInsuranceCorps.class);
        TmInsuranceCorps tmInsuranceCorps = TmInsuranceCorps.dao.findById(user.getId());
        if (tmInsuranceCorps.update()) {
            renderJsonRet(tmInsuranceCorps);
            return;
        } else {
            renderJsonError(40003);
            return;
        }
    }


    /**
     *返回日历图数据
     */
    public void personList() {
        PersonScheduling ps = (PersonScheduling) getReqBodyObject(PersonScheduling.class);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();

        // 开始时间
        String month = ps.getMonth() < 10 ? "0" + ps.getMonth() : ps.getMonth() + "";
        String startDate = ps.getYear() + "-" + month + "-01";
        Date sDate = null;
        try {
            sDate = sdf.parse(startDate);
        } catch (ParseException e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(sDate);
        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        int preDays = week - 1;
        cal.add(Calendar.DAY_OF_YEAR, -1 * preDays);
        sDate = cal.getTime();

        // 结束时间
        Date temp = null;
        try {
            temp = sdf.parse(ps.getYear() + "-" + month + "-01");
        } catch (Exception e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(temp);
        String endDate = ps.getYear() + "-" + month + "-" + cal.getActualMaximum(Calendar.DAY_OF_MONTH) + "";
        Date eDate = null;
        try {
            eDate = sdf.parse(endDate);
        } catch (ParseException e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(eDate);
        week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        int sufDays = 7 - week;
        cal.add(Calendar.DAY_OF_YEAR, sufDays);
        eDate = cal.getTime();
        String dateString = sdf.format(sDate);
        String dateStringe = sdf.format(eDate);
        List<String> list = new ArrayList<String>();

        for(int i = 0;i< 35;i++){
            if(i==0){
                list.add(dateString);
            }else{
                if(list.size() == 0){
                    Long d = sDate.getTime()+86400000;
                    Date day = new Date(d);
                    String statusDate =  sdf.format(day);
                    //String []str = statusDate.split("-");
                    list.add(statusDate);
                }else{
                    Date da = null;
                    try {
                        da = sdf.parse(list.get(list.size()-1));
                    } catch (ParseException e) {
                        renderJsonError(40008);
                        return;
                    }
                        Long d = da.getTime()+86400000;
                        Date day = new Date(d);
                        String statusDate =  sdf.format(day);
                        //String []str = statusDate.split("-");
                        list.add(statusDate);
                }
            }
        }

        List<String> dateList = new ArrayList<String>();
        for(int i = 0;i < list.size();i++){
            String []str = list.get(i).split("-");
            dateList.add(str[2]);
        }
        renderJsonRet(dateList);
    }


    /** GET
     * @Author: chen
     * @Description:根据医生id查询医生的保险团服务是否存在并开通
     * @Date: 10:44 2018/11/22
     * @param: [
     *              doctorId    ---医生id
     *          ]
     * @return: void
     */
    public void findInsuranceById(){
        try {
            String doctorId = getPara("doctorId");
            boolean isStatus = TmInsuranceCorps.dao.findInsuranceById(doctorId);
            renderJsonRet(isStatus);
        }catch (Exception e){
            renderJsonError(50002,"医生保险团服务查询失败");
        }
    }



   /* private List<ClassServiceRefEmpManagement> convert(Date start, Date end, int currentMonth, BigInteger userId, boolean isExchange) {
        Calendar cal = Calendar.getInstance();

        List<ClassServiceRefEmpManagement> rets = ClassServiceRefEmpManagement.dao.selectByUser(DateKit.toStr(start, "yyyy-MM-dd"), DateKit.toStr(end, "yyyy-MM-dd"), userId);
        Map<String, ClassServiceRefEmpManagement> map = Maps.newHashMap();
        for (ClassServiceRefEmpManagement ret : rets) {
            map.put(DateKit.toStr(ret.getDateTime(), "yyyy-MM-dd"), ret);
        }
        List<ClassServiceRefEmpManagement> ret = Lists.newArrayList();
        cal.setTime(start);
        while (true) {
            if (cal.getTime().getTime() > end.getTime()) {
                break;
            }

            ClassServiceRefEmpManagement csrem = map.get(DateKit.toStr(cal.getTime(), "yyyy-MM-dd"));
            if (csrem == null) {
                csrem = new ClassServiceRefEmpManagement();
                csrem.setClassType(0);
            }
            csrem.setDay(cal.get(Calendar.DAY_OF_MONTH));
            int week = cal.get(Calendar.DAY_OF_WEEK)-1;
            if (week < 0) week = 0;
            csrem.setWeek(week);
            if (cal.get(Calendar.MONTH) + 1 == currentMonth) {
                csrem.setIsCurrentMonth(true);
            } else {
                csrem.setIsCurrentMonth(false);
            }
            if (isExchange && (csrem.getClassType() == 3 || csrem.getClassType() == 4)) {
                ClassServiceWorkflow wf = ClassServiceWorkflow.dao.selectByUserDate(userId, csrem.getId());
                if (wf == null) {
                    csrem.setIsActive(true);
                } else {
                    csrem.setIsActive(false);
                }
            }
            if (csrem.getClassType() == 1 || csrem.getClassType() == 5) {
                csrem.setSections(ClassServiceClassSection.dao.selectAllByCid(csrem.getClassesId()));
            }

            ret.add(csrem);
            cal.add(Calendar.DAY_OF_YEAR, 1);
        }

        return ret;
    }*/
}
